package cn.onein.edu.web.controller;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.onein.edu.biz.bean.User;
import cn.onein.edu.util.StringUtil;
import cn.onein.edu.web.common.base.BaseController;
import cn.onein.edu.web.jms.producer.SendMailProducer;
import cn.onein.edu.web.service.LoginService;
import cn.onein.edu.web.util.AjaxCallBackJsonUtil;
import cn.onein.edu.web.vo.AjaxCallbackVO;

/**
 * 登陆，注销控制器
 * 
 * @author Upton
 * 
 */
@Controller
public class LoginController extends BaseController {

	Logger logger = Logger.getLogger(LoginController.class);

	@Autowired
	private LoginService loginService;

	@Autowired
	private SendMailProducer sendMailProducer;


	/**
	 * 登录
	 * 
	 * @param req
	 * @param action
	 *            action=login就是登录命令
	 * @param userName
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "/login2", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView login1(HttpServletRequest req, HttpServletResponse resp,
			String action, String userName, String password) {
		return login(req, resp, action, userName, password, "login");
	}
	
	@RequestMapping(value = "/login", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView login2(HttpServletRequest req, HttpServletResponse resp,
			String action, String userName, String password) {
		return login(req, resp, action, userName, password, "login2");
	}
	
	private ModelAndView login(HttpServletRequest req, HttpServletResponse resp,
			String action, String userName, String password, final String jspName){
		if (action == null || "".equals(action.trim())) {
			// 登陆初始页面
			ModelAndView mv = new ModelAndView(jspName);

			setMenu(mv, MENU_VALUE_LOGIN);
			return mv;
		} else if ("login".equals(action)) {
			// 登陆按钮点击
			String lastIP = req.getRemoteAddr();
			User user = loginService.login(userName,StringUtil.string2MD5(password), lastIP);

			if (user != null) {
				// 设置用户信息
				req.getSession(true).setAttribute(SESSION_USER_KEY, user);
				String savepassword = req.getParameter("savepassword");

				if (savepassword != null && "true".equals(savepassword)) {
					// 记住用户登录 ，记录Cookie
					Cookie cookieName = new Cookie(COOKIE_KEY_USER, userName);
					// 用户密码经过一次加密
					Cookie cookiePass = new Cookie(COOKIE_KEY_PASS, StringUtil.firstMD5(password));

					cookieName.setMaxAge(31536000);// 一年
					cookiePass.setMaxAge(31536000);// 一年
					
					resp.addCookie(cookieName);
					resp.addCookie(cookiePass);
				}

				return new ModelAndView("success");
			} else {
				ModelAndView mv = new ModelAndView(jspName);

				mv.addObject("userName", userName);

				mv.addObject(ERROR_MESSAGE_KEY, "登录失败，登录账号或密码错误！");
				setMenu(mv, MENU_VALUE_LOGIN);
				return mv;
			}
		} else if ("redirect".equals(action)) {
			// 权限控制不通过后的登陆的重定向
			ModelAndView mv = new ModelAndView("redirect:/login?type=redirect");

			return mv;
		} else {
			ModelAndView mv = new ModelAndView(jspName);

			setMenu(mv, MENU_VALUE_LOGIN);
			return mv;
		}
	}

	
	/**
	 * 退出登录
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/logout", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView logout(HttpServletRequest req,HttpServletResponse resp) {
		HttpSession session = req.getSession();
		if (session != null) {
			session.invalidate();
		}
		
		Cookie[] cookies = req.getCookies();
		if(cookies != null){
			for(Cookie cookie : cookies){
				if(BaseController.COOKIE_KEY_USER.equals(cookie.getName())){
					cookie.setValue(null);
					cookie.setMaxAge(0);
					resp.addCookie(cookie);
				} else if(BaseController.COOKIE_KEY_PASS.equals(cookie.getName())){
					cookie.setValue(null);
					cookie.setMaxAge(0);
					resp.addCookie(cookie);
				}
			}
		}

		return new ModelAndView("redirect:/login?type=logout");
	}

	/**
	 * 进入忘记密码页面
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/forgetPaassword", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView forgetPassword(HttpServletRequest req) {

		ModelAndView mv = new ModelAndView("forgetpassword");
		
		setMenu(mv, MENU_VALUE_LOST_PASSWORD);
		return mv;
	}

	/**
	 * 忘记密码操作
	 * 
	 * @param req
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/doForgetPassword.json", method = { RequestMethod.GET,
			RequestMethod.POST })
	public void doForgetPassword(String userName, HttpServletRequest req,
			HttpServletResponse resp) throws IOException {

		User user = loginService.getUserByName(userName);

		if (user == null) {
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(VALIDATE_NOTEXIST_KEY),resp);
			return;
		}
		
		String randomPass = StringUtil.generateRandomPassword();
		String md5Pass = StringUtil.string2MD5(randomPass);

		try{
			loginService.updateUserPassword(md5Pass, user.getId());

			sendMailProducer.sendPasswordRetrieveMessage(user.getEmail(),randomPass);
		}catch(Exception e){
			logger.error("forget password error.", e);
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXERROR),resp);
			return;
		}

		AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(AJAXSUCCESS), resp);
	}
}
